﻿<%@ WebHandler Language="C#" Class="CheckCodeHandler" %>

using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using Net.Ntalent.Action50.Core.Service;

/// <summary>
/// 负责处理关于验证码的所有操作的类，实现IHttpHandler接口。
/// </summary>
/// <author>王彦博</author>
public class CheckCodeHandler :Page, IHttpHandler, IRequiresSessionState
{
    /// <summary>
    /// 处理器默认处理方法，在此方法中将根据获取的动作参数分派特定的方法来作处理。
    /// </summary>
    /// <param name="context">
    /// http请求的上下文信息
    /// </param>
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        string action = context.Request["action"];
        switch (action)
        {
            case "getImage":
                byte[] imageArray = this.GetImage();
                context.Response.ContentType = "image/Gif";
                context.Response.OutputStream.Write(imageArray, 0, imageArray.Length);
                context.Response.Flush();
                break;
            case "check":
                context.Response.Write(this.Check(context));
                break;
        }
    }

    /// <summary>
    /// 接口HttpHandler必须实现的属性，
    ///</summary>
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    /// <summary>
    /// 在此方法中获取一张验证码图片。
    /// </summary>
    /// <returns>
    /// 代表验证码图片的byte数组
    /// </returns>
    private byte[] GetImage()
    {
        // 声明返回对象
        byte[] resultArray = null;

        // 调用AuthenticationService获取图片数据。
        using (var authenticationService = new AuthenticationService())
        {
            resultArray = authenticationService.CreateCheckCodeImage(
                authenticationService.GenerateCheckCode());
        }
        return resultArray;
    }

    /// <summary>
    /// 调用Authentication的比较方法来比较用户输入的数值是否正确.
    /// </summary>
    /// <param name="context">
    /// http请求的上下文信息
    /// </param>
    public string Check(HttpContext context)
    {
        return new AuthenticationService().CompareCheckCodes(context.Request["iputCheckCode"]) ?
           "true" : "false";  // 直接返回boolean会产生javaScript不能识别的大写的 True和False
    }
}

